package com.goldcn.goods.service;

import com.goldcn.common.CommonTools;
import com.goldcn.common.HttpUtil;
import com.goldcn.common.exception.ServiceException;
import com.goldcn.common.model.DataResult;
import com.goldcn.common.util.IdGen;
import com.goldcn.config.ProConstants;
import com.goldcn.enumeration.ErrorCodeEnum;
import com.goldcn.enumeration.GoodsStateEnum;
import com.goldcn.goods.dao.GoodsInfoMapper;
import com.goldcn.goods.dto.GoodsInfoWithFristSkuDto;
import com.goldcn.goods.vo.GoodsIndexInfoVo;
import com.goldcn.interceptor.SystemContext;
import com.goldcn.order.dao.ErrorEsMapper;
import com.goldcn.order.model.ErrorEs;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.List;

/**
 * Created by Administrator on 2016/11/24.
 */
@Service
public class GoodsIndexService {

    @Autowired
    RestTemplate restTemplate;
    @Autowired
    private GoodsInfoMapper goodsInfoMapper;
    @Autowired
    private ErrorEsMapper errorEsMapper;
    @Autowired
    private GoodsService goodsService;


    private Logger logger = Logger.getLogger(GoodsService.class);


    public void operateIndexing(GoodsStateEnum goodsState, Long goodsID) {
        switch (goodsState) {
            case Approved:
                addIndexing(goodsID);
                break;
            case Unshelve:
                deleteIndexing(goodsID);
                break;
            case Detele:
                deleteIndexing(goodsID);
                break;
            default:
                return;
        }
    }


    /**
     * 创建索引
     *
     * @param goodsID
     * @return
     */
    public boolean addIndexing(Long goodsID) {
        try {
            GoodsIndexInfoVo index = new GoodsIndexInfoVo();
            GoodsInfoWithFristSkuDto goodsInfo = goodsInfoMapper.selectByPrimaryKeyWithFristSku(goodsID);
            index.setGoodsID(goodsInfo.getGoodsID());
            index.setGoodsName(goodsInfo.getName());
            index.setGoodsUrl(goodsInfo.getImg());
            if (goodsService.getIsBocgold()) {
                index.setPrice(goodsInfo.getSkuPrice());
            } else {
                index.setPrice(goodsInfo.getPrice());
            }
            index.setVipmPrice(goodsInfo.getVipmPrice() == null ? new BigDecimal(-1) : goodsInfo.getVipmPrice());
            index.setViphPrice(goodsInfo.getViphPrice() == null ? new BigDecimal(-1) : goodsInfo.getViphPrice());
            JSONObject object = JSONObject.fromObject(goodsInfo.getAttrJson());
            index.setSku(object.containsKey("name") ? object.getString("name") : null);
            index.setSalas(goodsInfo.getSales());
            index.setClassifyName(goodsInfo.getClassifyName());
            index.setSubClassifyName(goodsInfo.getSubClassifyName());
            index.setSupplierName(goodsInfo.getSupplierName());
            index.setAddTime(goodsInfo.getAddTime());
            index.setLabel(goodsInfo.getLabelName());
            index.setCompanyID(goodsInfo.getCompanyID() + "");
            index.setPriceType(goodsInfo.getPriceType());

            logger.info("index=="+index);
            DataResult result = HttpUtil.httpPost(ProConstants.ESURL + "/goods/newIndex", index, restTemplate);
            if (result.getIsSuccess() == 0) {
                throw new ServiceException(result.getErrorDesc(), result.getErrorCode());
            }
        } catch (ServiceException se) {
            throw se;
        } catch (Exception e) {
            logger.info(e.getMessage());
            throw CommonTools.createException(ErrorCodeEnum.operateGoodsIndexingFailure);
        }
        return true;
    }

    /**
     * 删除索引
     *
     * @param goodsID
     * @return
     */
    public boolean deleteIndexing(Long goodsID) {
        try {
            DataResult result = HttpUtil.httpPost(ProConstants.ESURL + "/goods/delIndex/" + goodsID,
                    null, restTemplate);
            if (result.getIsSuccess() == 0) {
                throw CommonTools.createException(ErrorCodeEnum.operateGoodsIndexingFailure);
            }
        } catch (ServiceException e) {
            throw CommonTools.createException(ErrorCodeEnum.operateGoodsIndexingFailure);
        }
        return true;
    }

    /**
     * 更新索引 全部更新
     *
     * @param goodsID
     * @return
     */
    public boolean updateIndexing(Long goodsID) {
        try {
            GoodsIndexInfoVo index = new GoodsIndexInfoVo();
            GoodsInfoWithFristSkuDto goodsInfo = goodsInfoMapper.selectByPrimaryKeyWithFristSku(goodsID);
            index.setGoodsID(goodsInfo.getGoodsID());
            index.setGoodsName(goodsInfo.getName());
            index.setGoodsUrl(goodsInfo.getImg());
            index.setPrice(goodsInfo.getPrice());
            index.setVipmPrice(goodsInfo.getVipmPrice() == null ? new BigDecimal(-1) : goodsInfo.getVipmPrice());
            index.setViphPrice(goodsInfo.getViphPrice() == null ? new BigDecimal(-1) : goodsInfo.getViphPrice());
            JSONObject object = JSONObject.fromObject(goodsInfo.getAttrJson());
            index.setSku(object.containsKey("name") ? object.getString("name") : null);
            index.setSalas(goodsInfo.getSales());
            index.setClassifyName(goodsInfo.getClassifyName());
            index.setSubClassifyName(goodsInfo.getSubClassifyName());
            index.setSupplierName(goodsInfo.getSupplierName());
            index.setAddTime(goodsInfo.getAddTime());
            index.setLabel(goodsInfo.getLabelName());

            DataResult result = HttpUtil.httpPost(ProConstants.ESURL + "/goods/index/", index, restTemplate);
            if (result.getIsSuccess() == 0) {
                throw CommonTools.createException(ErrorCodeEnum.operateGoodsIndexingFailure);
            }
            return true;
        } catch (Exception e) {
            logger.info(e.getMessage());
            throw CommonTools.createException(ErrorCodeEnum.operateGoodsIndexingFailure);
        }
    }

    /**
     * 片段修改 支持价格修改
     *
     * @param index
     * @return
     */
    public boolean updateIndexingSelective(GoodsIndexInfoVo index) {
        try {
            HttpUtil.httpPost(ProConstants.ESURL + "/goods/index/", index, restTemplate);
            return true;
        } catch (Exception e) {
            throw CommonTools.createException(ErrorCodeEnum.operateGoodsIndexingFailure);
        }
    }

    @Transactional
    public String correction(List<GoodsIndexInfoVo> indexInfoist) {
        for (GoodsIndexInfoVo indexInfo : indexInfoist) {
            GoodsInfoWithFristSkuDto goodsInfo = goodsInfoMapper.selectByPrimaryKeyWithFristSku(indexInfo.getGoodsID());
            ErrorEs errorEs = new ErrorEs();
            errorEs.setId(IdGen.get().nextId());
            errorEs.setType(1);
            errorEs.setObjectID(goodsInfo.getGoodsID());
            if (goodsInfo == null) {
                errorEs.setReason(1);
            } else {
                GoodsIndexInfoVo localIndexInfo = new GoodsIndexInfoVo();
                BeanUtils.copyProperties(goodsInfo, localIndexInfo);
                if (indexInfo.equals(localIndexInfo)) {
                    continue;
                }
                errorEs.setReason(2);
            }
            errorEsMapper.insert(errorEs);
        }
        return "success";
    }

    public Object updateIndexingToGoldPrice(){
        List<Long> goodsIDs = goodsInfoMapper.selectAll(SystemContext.getCompanyID(),1);
        for (Long goodsID : goodsIDs){
            GoodsIndexInfoVo goodsIndexInfoVo = new GoodsIndexInfoVo();
            goodsIndexInfoVo.setGoodsID(goodsID);
            goodsIndexInfoVo.setPriceType(0);
            updateIndexingSelective(goodsIndexInfoVo);
        }
        return "success";
    }

}
